package com.jicheng.Utils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件操作工具
 */

public class FileHandleUtils {
    /**
     * docx文件转换成html
     *
     * @param tempPath
     *            文件存放路径
     * @param fileName
     *             path+fileName
     * @param outPutFile
     *            预览html path+fileName
     */
    public static void docxToHtml(String tempPath, String fileName, String outPutFile)
            throws TransformerException, IOException, ParserConfigurationException {

        XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));
        XHTMLOptions options = XHTMLOptions.create().indent(4);
        File imageFolder = new File(tempPath);
        options.setExtractor(new FileImageExtractor(imageFolder));
        options.URIResolver(new FileURIResolver(imageFolder));
        File outFile = new File(outPutFile);
        outFile.getParentFile().mkdirs();
        OutputStream out = new FileOutputStream(outFile);

        XHTMLConverter.getInstance().convert(document, out, options);

    }
public static void main(String args[]){
    try {
        HSSFToHtml("H:\\test","H:\\test\\fff.xls","H:\\test\\fff.html");
    } catch (TransformerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}


    /**
     * doc文件转换成html
     */
    public static void docToHtml(String tempPath, String fileName, String outPutFile)
            throws TransformerException, IOException, ParserConfigurationException {

        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
                                      float heightInches) {
                return "img/" + suggestedName;
            }
        });
        wordToHtmlConverter.processDocument(wordDocument);
        List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                Picture pic = (Picture) pics.get(i);
                try {
                    pic.writeImageContent(new FileOutputStream(tempPath + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        writeFile(new String(out.toByteArray()), outPutFile);
    }

    /**
     * excel .xls文件转换成html
     */
    public static void HSSFToHtml(String tempPath, String fileName, String outPutFile)
            throws TransformerException, IOException, ParserConfigurationException {

        InputStream input = new FileInputStream(fileName);
        HSSFWorkbook excelBook = new HSSFWorkbook(input);
        ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        excelToHtmlConverter.processWorkbook(excelBook);
        List pics = excelBook.getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                Picture pic = (Picture) pics.get(i);
                try {
                    pic.writeImageContent(new FileOutputStream(tempPath + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        Document htmlDocument = excelToHtmlConverter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        outStream.close();

        writeFile(new String(outStream.toByteArray()), outPutFile);
    }

    /**
     * 将文件内容写入指定html文件
     * @param content 内容
     * @param outFilePath 输出文件路径 path+fileName
     */
    private static void writeFile(String content, String outFilePath) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(outFilePath);
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
            bw.write(content);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (fos != null)
                    fos.close();
            } catch (IOException ie) {
            }
        }
    }

    /*文件下载*/
    public static boolean downloadFile(String filePath, String fileName, String downloadName,String contentType, HttpServletResponse response){
        boolean flag=true;
        try {
            File file = new File(filePath + fileName);
            if (!file.exists()) {
                flag = false;
            } else {
                FileInputStream fileInputStream = new FileInputStream(file);
                response.setHeader("Content-Disposition",
                        "attachment;Filename=" + URLEncoder.encode(downloadName, "UTF-8"));
                response.setHeader("Content-Type", contentType);//设置格式类型
                OutputStream outputStream = response.getOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = fileInputStream.read(bytes)) > 0) {
                    outputStream.write(bytes, 0, len);
                }
                fileInputStream.close();
                outputStream.close();
            }
        }catch (IOException e){
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}
